<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智能浴室系统</title>
    <link rel="stylesheet" href="/css/index.css" />
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <!-- 引入样式 -->
    <link
            rel="stylesheet"
            href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
    />
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="/js/easytimer.js"></script>

</head>
<body>
<div id="app" :style="value1?'':'background-image: linear-gradient(to right, #E94E65, #15A892 20%, #A89215 80%, #1574A8);'" class="index">
    <div style="position: absolute;top: 20px;right: 40px;" class="change-bg">
        <el-switch
                v-model="value1"
                inactive-text="切换背景">
        </el-switch>
    </div>
    <div style="display: flex;align-items: center" class="header">


<!--        <el-button   round>我的订单</el-button>-->

        <el-dialog style="z-index: 1000;" title="订单列表" :visible.sync="dialogOrder">


            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="全部" name="first">
                    <el-table :data="userRecordList">
                        <el-table-column property="id" label="订单编号" width="250"></el-table-column>
                        <el-table-column property="startTime" label="创建时间" width="200"></el-table-column>
                        <el-table-column property="endTime" label="结束时间" width="200"></el-table-column>
                        <el-table-column property="equipment.index" label="设备编号"></el-table-column>
                        <el-table-column property="amount" label="消费金额(元)"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="进行中" name="second">
                    <el-table :data="DoingRecord">
                        <el-table-column property="id" label="订单编号" width="250"></el-table-column>
                        <el-table-column property="startTime" label="创建时间" width="200"></el-table-column>
                        <el-table-column property="endTime" label="结束时间" width="200"></el-table-column>
                        <el-table-column property="equipment.index" label="设备编号"></el-table-column>
                        <el-table-column property="amount" label="消费金额(元)"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="已完成" name="third">
                    <el-table :data="DoneRecord">
                        <el-table-column property="id" label="订单编号" width="250"></el-table-column>
                        <el-table-column property="startTime" label="创建时间" width="200"></el-table-column>
                        <el-table-column property="endTime" label="结束时间" width="200"></el-table-column>
                        <el-table-column property="equipment.index" label="设备编号"></el-table-column>
                        <el-table-column property="amount" label="消费金额(元)"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="预约" name="fourth">
                    <el-table :data="PreRecord">
                        <el-table-column property="id" label="订单编号" width="250"></el-table-column>
                        <el-table-column property="startTime" label="创建时间" width="200"></el-table-column>
                        <el-table-column property="endTime" label="结束时间" width="200"></el-table-column>
                        <el-table-column property="equipment.index" label="设备编号"></el-table-column>
                        <el-table-column property="amount" label="消费金额(元)"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="故障" name="fifth">
                    <el-table :data="ErrorRrcord">
                        <el-table-column property="id" label="订单编号" width="250"></el-table-column>
                        <el-table-column property="startTime" label="创建时间" width="200"></el-table-column>
                        <el-table-column property="endTime" label="结束时间" width="200"></el-table-column>
                        <el-table-column property="equipment.index" label="设备编号"></el-table-column>
                        <el-table-column property="amount" label="消费金额(元)"></el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="已取消" name="sixth">
                    <el-table :data="CancelRecord">
                        <el-table-column property="id" label="订单编号" width="250"></el-table-column>
                        <el-table-column property="startTime" label="创建时间" width="200"></el-table-column>
                        <el-table-column property="endTime" label="结束时间" width="200"></el-table-column>
                        <el-table-column property="equipment.index" label="设备编号"></el-table-column>
                        <el-table-column property="amount" label="消费金额(元)"></el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

        </el-dialog>
    </div>
    <el-drawer
            title="个人中心"
            :visible.sync="drawer"
            :direction="direction"
            :before-close="handleClose"
            style="text-align: center"
    >
        <div style="text-align: center" class="demo-image__preview">
            <div class="no-login" v-if="!userInfo">您还没有登录哦</div>
            <div class="userinfo " v-if="userInfo">
                <el-image
                        style="width: 100px; height: 100px"
                        :src="url"
                        :preview-src-list="srcList"
                >
                </el-image>
            <p> <el-button class="userinfo-btn" type="primary" plain><label for="">用户名:</label>{{userInfo.loginName}}</el-button> </p>
            <p> <el-button class="userinfo-btn" type="primary" plain><label for="">性  别:</label>{{userInfo.sex}}</el-button> </p>
            <p> <el-button class="userinfo-btn" type="primary" plain><label for="">学  校:</label>{{userInfo.school}}</el-button> </p>
                <p> <el-button class="userinfo-btn" type="primary" plain><label for="">余  额:</label>{{userInfo.amount}}</el-button> </p>
                <p> <el-button class="userinfo-btn" type="primary" plain><label for="">积  分:</label>{{userInfo.integral}}</el-button> </p>
            <p> <el-button class="userinfo-btn" type="primary" plain><label for="">一卡通:</label>{{userInfo.campusCard}}</el-button></p>
            <p> <el-button  class="userinfo-btn" type="primary" plain><label for="">手机号:</label>{{userInfo.mobile}}</el-button></p>




            <el-button type="text" @click="centerDialogVisible = true">修改个人信息</el-button>
                <el-button type="text" @click="recharge = true">余额充值</el-button>
            <el-dialog
                    title="修改个人信息"
                    :visible.sync="centerDialogVisible"
                    width="30%"
                    center>
                <el-input style="margin:10px" v-model="modifyUserData.loginName" placeholder="请输入用户名"></el-input>
                <el-input style="margin:10px" v-model="modifyUserData.password" placeholder="请输入密码"></el-input>
                <el-input style="margin:10px" v-model="pwd2" placeholder="确认密码"></el-input>
                <el-input style="margin:10px" v-model="modifyUserData.mobile" placeholder="请输入手机号"></el-input>

                <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="modifyUser">确 定</el-button>
  </span>
            </el-dialog>


                <p> <el-button v-if ="userInfo.alipay" class="userinfo-btn" type="primary" plain><label for="">支付宝:</label>{{userInfo.alipay+''}}</el-button> </p>
                <p> <el-button  v-if ="userInfo.wechat" class="userinfo-btn" type="primary" plain><label for="">微  信:</label>{{userInfo.wechat+' '}}</el-button> </p>
                <p> <el-button  v-if ="userInfo.bankCard" class="userinfo-btn" type="primary" plain><label for="">银行卡:</label>{{userInfo.bankCard+' '}}</el-button> </p>
                <div>  <el-button type="text" @click="accountDiglog = true">第三方账号绑定</el-button></div>
               
                <el-dialog
                        title="第三方账号绑定"
                        :visible.sync="accountDiglog"
                        width="30%"
                        center>
                    <el-input style="margin:10px" v-model="account.alipay" placeholder="支付宝"></el-input>
                    <el-input style="margin:10px" v-model="account.wechat" placeholder="微信"></el-input>
                    <el-input style="margin:10px" v-model="account.bankCard" placeholder="银行卡"></el-input>

                    <span slot="footer" class="dialog-footer">
    <el-button @click=" accountDiglog = false">取 消</el-button>
    <el-button type="primary" @click="modAccount">确 定</el-button>
  </span>
                </el-dialog>

                <el-dialog
                        title="提示"
                        :visible.sync="recharge"
                        width="30%"
                        :before-close="handleClose">
                    <div style="margin-top: 15px;">
                        <el-input placeholder="请输入内容" v-model="rechargeNum" class="input-with-select">
                            <el-select style="width: 150px;" v-model="payType"  slot="prepend" placeholder="请选择充值方式">
                                <el-option label="支付宝" value="1"></el-option>
                                <el-option label="微信" value="2"></el-option>
                                <el-option label="银行卡" value="3"></el-option>
                            </el-select>
                        </el-input>
                    </div>
                    <span slot="footer" class="dialog-footer">
    <el-button @click="recharge = false">取 消</el-button>
    <el-button type="primary" @click="rechargeAmount">确 定</el-button>
  </span>
                </el-dialog>
            </div>
        </div>

        <el-button v-if="userInfo"
                @click="logout"
                style="
            position: absolute;
            bottom: 100px;
            left: 50%;
            transform: translateX(-50%);
          "
                type="warning"
                round
        >退出登录</el-button
        >
        <el-button v-if="!userInfo"
                style="
            position: absolute;
            bottom: 100px;
            left: 50%;
            transform: translateX(-50%);
          "
                type="warning"
                round
                   @click="login"
        >登录</el-button
        >
    </el-drawer>
    <div class="bg">
        <h1>智能浴室系统<span>{{userInfo?'——'+userInfo.sex+'浴室':' '}}</span></h1>
        <h4>欢迎来到智能浴室</h4>
        <div class="info">
<!--            <p>当前页可用设备：{{canUse.length}}</p>-->
        </div>
        <el-dialog
                title="请输入使用时长：(单位分)"
                :visible.sync="inputTimeDialog"
                width="30%"
                center>
            <el-time-picker
                    v-model="value3"
                    :picker-options="{
      selectableRange: '12:30:00 - 20:30:00'
    }"
                    placeholder="输入预约时间点">
            </el-time-picker>

                <el-input style="margin-top: 30px" v-model="useTime" placeholder="请输入使用时间（10-45分钟）"></el-input>

            <span slot="footer" class="dialog-footer">
    <el-button @click="inputTimeDialog = false">取 消</el-button>
    <el-button type="primary" @click="useConfirm(currentItemIndex,currentId,'not-pre')">确 定</el-button>
  </span>
        </el-dialog>


        <el-dialog
                title="请输入预约时长：(单位分)"
                :visible.sync="yuyueTimeDialog"
                width="30%"
                center>

            <el-time-picker
                    v-model="value2"
                    is-range
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                    :picker-options="{
                selectableRange: ['12:30:00 - 21:00:00', '12:30:00 - 21:30:00']
                }">

            </el-time-picker>

            <span slot="footer" class="dialog-footer">
    <el-button @click="yuyueTimeDialog = false">取 消</el-button>
    <el-button type="primary" @click="useConfirm(currentItemIndex,currentId,'pre')">确 定</el-button>
  </span>
        </el-dialog>

        <div v-show="index===0" style="margin-top: 100px;" class="bar">
            <div class="item order">
                洗浴
                <div class="content">
                    <div @click="openBathroom" class="yuwei">浴位</div>
                    <div @click="mall = true" class="yuwei">商城</div>
                </div>
            </div>

            <div  @click="getUserRecordList()" class="item">订单</div>
            <div round @click="drawer = true" class="item">

                <div v-if="userInfo" style="margin-right: 20px;"  class="user">
                    <el-avatar
                            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                    ></el-avatar>

                </div>
                <div v-else style="margin-right: 20px;" > 点击登录</div>
            </div>

        </div>

        <div class="mall">
            <el-drawer
                    title="积分商城"
                    :visible.sync="mall"
                    direction="ltr"
                    :before-close="handleClose">
                <div style="padding:20px;display: flex;flex-wrap: wrap;overflow: hidden">
                   
                            <el-card v-for="(item,index) in redPackage" :key="index" style="margin: 20px;width: 200px;" :body-style="{ padding: '0px' }">
                                <img src="https://s3.ax1x.com/2021/03/13/6wDvKU.png" class="image">
                                <div style="padding: 14px;">
                                    <span>{{item.title}}</span>
                                    <div class="bottom clearfix">

                                        <el-button @click="exchange(item.amount,item.integral)" type="text" class="button">兑换</el-button>
                                    </div>
                                </div>
                            </el-card>

                </div>
            </el-drawer>
        </div>

        <div v-show="index===1" class="box show">
            <el-button @click="index=0" class="goback" type="primary" icon="el-icon-back">返回</el-button>
            <div
                    :style="item.status==='NOT_USE'?'background:#67C23A':item.status==='CAN_PRE'?'background:#409EFF':item.status==='USEING'?'background:#F56C6C':'background:#909399'"
                    v-for="(item,index) in equipments"
                    :key="index"
                    class="inner"
            >
                <div class="item-info">
                    <p>{{params.pagination+'—'+index+'号'}}</p>

                    <p>
                        {{item.status==='NOT_USE'?"空闲中":item.status==="CAN_PRE"?"已预约":item.status==='USEING'?'':'设备故障'}}
                    </p>

                    <div v-if="item.time>0">{{item.countDown}}</div>
                    <div v-else>

                    <p v-if="item.status ==='USEING'&&preTime>0">
                        请在{{`${value3.getHours()}:${value3.getMinutes()}:${value3.getSeconds()}`}} 前到达浴室开始洗浴
                    </p>
                    <p v-if="item.status ==='USEING'&&useTime>=0&&seconds>0&&preTime<=0">
                        当前使用时长：{{useTime}} 分:{{seconds}}秒
                    </p>
                    </div>
                </div>

                <div
                        v-if="item.status==='USEING'&&currentItemIndex!=index"
                        class="action"
                        style="background: #d0d3d8; color: black"
                        @click="preUse(index,item.id)"
                >
                   预约
                </div>
                <div v-if="currentId===item.id" class="action" @click="cancelUse(index,item.id)">取消使用</div>
                <div v-if="item.status==='NOT_USE'" class="action" @click="use(index,item.id)">点击使用</div>
            </div>
            <div class="page">
                <el-pagination background layout="prev, pager, next" :total="total" :current-page="params.pagination" :page-size="params.PageSize" @current-change="pageChange">
                </el-pagination>
            </div>
        </div>

    </div>
</div>
<script src="/js/api.js"></script>

<script>
     var timerInstance = new easytimer.Timer();
     console.log(timerInstance)
     let hello="hello";
    var app = new Vue({
        el: "#app",
        data: {
            yuyueTimeDialog:false,
            showEquipment:false,
            isLogin:false,
            total:50,
            mall:false,
            index:0,
            useTime:null,
            payType:'',
            hello:hello,
            recharge:false,
            TimerI:this.timerInstance,
            websocket:null,
            rechargeNum:0,
            params:{pagination:1,pageSize:9,location:"男"},
            centerDialogVisible: false,
            message: "Hello Vue!",
            count: "",
            dialogOrder:false,
            activeName:"first",
            currentId:null,
            seconds:60,
            value1: true,
            drawer: false,
            userInfo:null,
            currentItemIndex:null,
            canUseEquipment:true,
            userId:"",
            pwd2:'',
            timer:null,
            currentTime:0,
            currentMinutes:0,
            direction: "rtl",
            duration:null,
            value2: [new Date(new Date().getFullYear(),  new Date().getMonth(), new Date().getDate(), 8, 40), new Date(new Date().getFullYear(),  new Date().getMonth(), new Date().getDate(), 12, 40)],
            useTimeCopy:0,
            inputTimeDialog: false,
            startTime:null,
            value3:'',
            endTime:null,
            accountDiglog:false,
            userRecordList:[],
            recordId:null,
            preTime:20,
            cancelCount:0,
            countDown:null,
            redPackage:[
                {
                    title:"洗浴一元红包（需100积分）",
                    amount:1,
                    integral:100,

                },
                {
                    title:"洗浴二元红包（需200积分）",
                    amount:2,
                    integral:200,
                },
                {
                    title:"洗浴三元红包（需300积分）",
                    amount:3,
                    integral:300,
                },
                {
                    title:"洗浴五元红包（需500积分）",
                    amount:5,
                    integral:500,
                },
            ],
            account:{
                alipay:'',
                wechat:'',
                bankCard:''
            }
            ,
            modifyUserData:{

                loginName:'',
                password:"",
                mobile:''
            },
            url:
                "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
            srcList: [
                "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
                "https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg",
            ],
            equipments: [],
        },
       async created() {
            // let timer = setInterval(this.decreate, 1000);
          //   console.log(this.TimerI)
          //  this.TimerI.start({countdown: true, startValues: {seconds: 1000}});
          //   setInterval(this.increateTime, 1000);
          //
          // setInterval(()=>{
          //     this.countDown = this.TimerI.getTimeValues().toString()
          // },1000)
            setInterval(()=>{
                this.currentTime++;
                if (this.currentTime>60){
                    this.currentTime=0;
                    this.currentMinutes++;
                }
                if ( this.currentMinutes>60){
                    this.currentMinutes=0;
                }
            },1000)
            let userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
              if (userInfo){
                  this.userInfo = userInfo;
                  this.userId = userInfo.id;
                  this.params.location = this.userInfo.sex;
                  this.$notify({
                      title: '成功',
                      message: '登录成功',
                      type: 'success'
                  });
                  if (this.userInfo.amount<=10){
                      this.$notify({
                          title: '余额不足',
                          message: '余额不足，请尽快充值哦',
                          type: 'warning'
                      });
                  }
                  this.initWebSocket(userInfo.loginName);
              }else {
                  this.$notify({
                      title: '警告',
                      message: '您还为登录哦',
                      type: 'warning'
                  });
              }


           //const response = await requests("/equipment/list","POST",{pagination:1,pageSize:1});
           const response = await this.getInitData();
           this.equipments = response.data.content;
           this.total = response.data.totalElements;

           this.equipments.map(e=>{
               return {
                   ...e,countDown:0
               }
           });

           this.equipments.forEach(e=>{
               if (e.time&&e.time>0){
                   let time = new easytimer.Timer();
                   time.start({countdown: true, startValues: {seconds: (e.time)*60}});
                 let setin =  setInterval(()=>{
                       e.countDown = "还剩 "+time.getTimeValues().toString().substr(0,5)+" 分钟";
                       console.log(time.getTimeValues().toString());
                   },1000);

                   time.addEventListener('targetAchieved',async ()=> {
                     clearInterval(setin);
                     e.time = 0
                       e.status = "NOT_USE";
                     console.log("finished");
                   const result =   await this.updateEquipmentStatus(e.id,"NOT_USE",0);
                    console.log(result);
                   });
               }

           })
        },
        destroyed() {
            this.websock.close() //离开路由之后断开websocket连接
        },
        computed: {
            canUse: function () {
                return this.equipments.filter(
                    (e) => e.status !== "BREAK" && e.status !== "USEING"
                );
            },
            DoingRecord:function fil() {
                return this.userRecordList.filter(e=>e.recordStatus==='DOING');
            },
            DoneRecord:function f() {
        return this.userRecordList.filter(e=>e.recordStatus==='DONE');
    },
    ErrorRrcord:function f1() {
        return this.userRecordList.filter(e=>e.recordStatus==='ERROR');
    },
    CancelRecord:function f2() {
        return this.userRecordList.filter(e=>e.recordStatus==='CANCEL');
    },
    PreRecord:function f3() {
        return this.userRecordList.filter(e=>e.recordStatus==='PRE');
    }
        },
        methods: {

            initWebSocket(name){ //初始化weosocket
                const wsuri = "ws://127.0.0.1:8080/socket/"+name;
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen(){ //连接建立之后执行send方法发送数据
                // let actions = {"test":"12345"};
                // this.websocketsend(JSON.stringify(actions));
            },
            websocketonerror(){//连接建立失败重连
                this.initWebSocket();
            },
            websocketonmessage(e){ //数据接收
                // alert(+"来消息啦");

                this.$notify({
                    title: '警告',
                    message: e.data,
                    type: 'warning'
                });
            },
            websocketsend(Data){//数据发送
                this.websock.send(Data);
            },
            websocketclose(e){  //关闭
                console.log('断开连接',e);
            },

           async rechargeAmount(){
                const result = await  requests("/user/modify","POST",
                    {id:this.userId,
                        amount:parseInt(this.userInfo.amount)+parseInt(this.rechargeNum)
                       });
                if (result.data){
                    this.$message({
                        showClose: true,
                        message: '充值成功',
                        type: 'success'
                    });
                    this.userInfo.amount = parseInt(this.userInfo.amount)+parseInt(this.rechargeNum);
                    this.recharge = false;
                }
            },

            handleClick(tab, event) {
                console.log(tab, event);
            },

            openBathroom(){
                const date = new Date();
                if (date.getHours()<9||date.getHours()>24) {
                    this.$message({
                        showClose: true,
                        message: '抱歉，当前不在浴室开放时间内（开放时间为：12:00 ——21:00）',
                        type: 'error'
                    });
                    return ;
                }

                this.index =1;
                
            },

            async exchange(amount,integral){
                if (this.userInfo.integral-integral<0){
                    this.$message({
                        showClose: true,
                        message: '抱歉，您当前积分不足',
                        type: 'error'
                    });
                    return ;
                }
                const result = await  requests("/user/modify","POST",
                    {id:this.userId,
                        amount:this.userInfo.amount+amount,
                        integral:this.userInfo.integral-integral});
                if (result.data){
                    this.$message({
                        showClose: true,
                        message: '兑换成功',
                        type: 'success'
                    });
                    this.userInfo.amount = parseInt(this.userInfo.amount)+amount;
                    this.userInfo.integral = parseInt(this.userInfo.integral)-integral;
                }
            },

           async modAccount(){
               console.log("save");
                var pattern = /^([1-9]{1})(\d{14}|\d{18})$/,
                   str = this.account.bankCard.trim().replace(/\s+/g, "");
              // if (str!==''&&!pattern.test(str)) {
              //     this.$message({
              //         showClose: true,
              //         message: '请输入正确银行卡',
              //         type: 'error'
              //     });
              //     return ;
              // }
               const result = await requests("/user/modify","POST",{id:this.userId,...this.account});
               if (result.data){
                   this.modDiglog = false
                   this.$message({
                       showClose: true,
                       message: '绑定成功',
                       type: 'success'
                   });
               }else{
                   this.$message({
                       showClose: true,
                       message: '绑定失败',
                       type: 'error'
                   });
               }
               
           },

            async getUserRecordList(){
                if (!this.userInfo){
                    this.$message({
                        showClose: true,
                        message: '请先登录哦',
                        type: 'warning'
                    });
                    return;
                }
                let result = await  requests("/userRecord/list","POST",{userId:this.userId});
                this.dialogOrder = true;
                if (result.data){
                    this.userRecordList = result.data.content;
                    console.log(this.userRecordList,"record");
                }


            },

            async insertUserRecord(){
                let result = await  requests("/userRecord/add","POST",
                    {userId:this.userId,
                        startTime:this.startTime,
                        endTime:new Date(),
                        equipmentId:this.currentId,
                        amount:(this.useTimeCopy-this.useTime)*0.5
                    ,recordStatus:"DOING"});
                if (result){
                    this.recordId = result.id;
                }
            },
           async modifyUser(){
               console.log("save");
           const result = await requests("/modify","POST",{id:this.userId,...this.modifyUserData});
           if (result.data){
               this.centerDialogVisible = false
               this.$message({
                   showClose: true,
                   message: '修改成功',
                   type: 'success'
               });
           }
            },
            //退出登录
            logout(){
                this.userInfo = null;
            },
            login(){
              window.location.href='/app/sign';
            },
            decreate: function () {
                const mydate = new Date();
                let hour = mydate.getHours();
                let min = mydate.getMinutes();
                let seconds = mydate.getSeconds();
                this.count = hour + ":" + min + ":" + seconds + " s";
            },

           async getInitData(){
                const result = await requests("/equipment/list","POST",this.params);
                this.equipments = result.data.content;
                return result;
                //console.log("result",result);
            },
           async pageChange(page){
               this.params.pagination=page;
               const result =await this.getInitData();

               console.log("pageChange",result);
             // window.alert(page)
            },
            handleClose(done) {
                this.$confirm("确认关闭？")
                    .then((_) => {
                        done();
                    })
                    .catch((_) => {});
            },
            preUse(index,id){
                if (!this.userInfo){
                    this.$message({
                        showClose: true,
                        message: '请先登录哦',
                        type: 'warning'
                    });
                    return;
                }
                if (!this.canUseEquipment) {
                    this.$message({
                        showClose: true,
                        message: '您当前已经存在订单啦',
                        type: 'warning'
                    });

                    return;
                }
                this.yuyueTimeDialog = true
                this.currentItemIndex = index;
                this.currentId = id;
            },
            use(index,id) {
               if (!this.userInfo){
                   this.$message({
                       showClose: true,
                       message: '请先登录哦',
                       type: 'warning'
                   });
                   return;
               }
               if (!this.canUseEquipment) {

                   this.$message({
                       showClose: true,
                       message: '您当前已经存在订单啦',
                       type: 'warning'
                   });
                   return;
               }
               if ((this.userInfo.permissions&&this.userInfo.permissions==='1')||this.cancelCount>=3){
                   this.$message({
                       showClose: true,
                       message: '抱歉，您当前存在恶意预约行为，不能使用。',
                       type: 'warning'
                   });
                   return;
                }
                this.inputTimeDialog = true;
               this.currentItemIndex = index;
                this.currentId = id;
            },

            async updateUserRecord(id,status){
                const result = requests("/userRecord/modifiy","POST",{
                    id:id,
                    amount:0,
                    recordStatus: status
                })

            },
            async cancelUse(index,id){
                if (this.preTime<=10){
                    this.$message({
                        showClose: true,
                        message: '已经过了取消时间哦',
                        type: 'warning'
                    });
                    return ;
                }
                this.equipments[index].status = "NOT_USE";
                this.useTime=0;
                await this.updateEquipmentStatus(id,"NOT_USE",0);
                await this.updateUserRecord(this.recordId,"CANCEL");
                const result = await  requests("/user/modify","POST",
                    {id:this.userId,
                        integral:this.userInfo.integral-10});
                this.userInfo.integral=this.userInfo.integral-10;
                this.canUseEquipment = true;
                this.cancelCount++;
                if (this.cancelCount>=3){
                    await requests("/user/modify","POST",{
                        id:this.userInfo.id,
                        permissions:"1",
                    })
                }
                if (this.timer) {
                    clearInterval(this.timer);
                }
            },
           async useConfirm(index,id,type){


               this.canUseEquipment = false;
                if (type==='pre'){
                    this.equipments[index].status = "CAN_PRE";
                     this.yuyueTimeDialog = false;
                    await this.updateEquipmentStatus(id,"CAN_PRE");
                    let result = await  requests("/userRecord/add","POST",
                        {userId:this.userId,
                            startTime:this.value2[0],
                            endTime:this.value2[1],
                            equipmentId:this.currentId,
                            recordStatus:"PRE"
                            // amount:(this.useTimeCopy-this.useTime)*0.5
                            });
                    this.$message({
                        showClose: true,
                        message: '预约成功',
                        type: 'success'
                    });
                } else{
                    if (this.useTime<10||this.useTime>45){
                        this.$message({
                            showClose: true,
                            message: '洗浴时间请在10-45分钟之内',
                            type: 'warning'
                        });
                        return;
                    }
                this.equipments[index].status = "USEING";
                this.equipments[index].time = 0;
                this.inputTimeDialog = false;
                this.useTimeCopy = this.useTime;
                let date = new Date();
                this.startTime = date;

               await this.updateEquipmentStatus(id,"USEING",this.useTime);
                    this.useTime--;
                    await this.insertUserRecord();
               this.timer =  setInterval(async()=>{

                   if(this.preTime===0){
                       this.$message({
                           showClose: true,
                           message: '请在10分钟内到达浴室',
                           type: 'warning'
                       });
                   }

                   if (this.preTime<=0){
                       if (this.seconds<=0){
                           if(this.useTime===10){
                               this.$message({
                                   showClose: true,
                                   message: '洗浴时间还剩下10分钟哦',
                                   type: 'warning'
                               });
                           }

                           if (this.useTime==0&&this.seconds==0){
                               console.log("洗完了");
                               this.endUse(index,id);
                               this.preTime = 10;
                               clearInterval(this.timer);
                           }
                           this.seconds=60;
                           this.useTime--;
                       }

                   }else {
                       if (this.seconds<=0){
                           this.seconds=60;
                           this.preTime--;
                       }
                   }
                   this.seconds--;

                },1000)
            }},
           async endUse(index,id) {
                if (!this.userInfo){
                    this.$message({
                        showClose: true,
                        message: '请先登录哦',
                        type: 'warning'
                    });
                    return;
                }
                this.equipments[index].status = "NOT_USE";
               await this.updateEquipmentStatus(id,"NOT_USE",0);
               //积分+5   -消费金额
               const amout = -((this.useTimeCopy-this.useTime)*0.5);

               this.userInfo.integral = parseInt(this.userInfo.integral)+5;

               this.userInfo.amount = parseInt(this.userInfo.amount+amout);

               await this.exchange(amout,-5);
              await this.updateUserRecord(this.recordId,(this.useTimeCopy-this.useTime)*0.5,"DONE")
                this.useTime = null;
                this.currentItemIndex = null;
                this.currentId = null;
            },
           async updateEquipmentStatus(id,status,time){
              let result = await requests("/equipment/modify","POST",{id:id,status:status,time:time,startTime:new Date()});
                   console.log(result);
            },

            increateTime() {
                this.equipments.forEach((e) => {
                    if (e.status === "USEING") {
                        e.second++;
                        if (e.second === 60) {
                            e.second = 0;
                            e.time++;
                        }
                    }
                });
            },
        },
        status: function (status) {
            let result = "";
            switch (status) {
                case "BREAK":
                    result = "不可以使用";
                    break;
                case "USEING":
                    result = "正在使用";
                    break;
                case "CAN_PRE":
                    result = "正在使用";
                    break;
                case "NOT_USE":
                    result = "可以使用";
                    break;
            }
            return result;
        },
    });
</script>
</body>
</html>
